package com.ruoyi.flow.listeners;

import com.ruoyi.flow.auth.security.FlowUser;
import com.ruoyi.flow.flow.FlowConstants;
import com.ruoyi.flow.flow.workflow.FlowService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkState;

import java.util.List;

/**
 * 获取用户的领导用户
 *
 * @Author: wtian
 * @Description:
 * @Date: Created in 20:17 2018/8/14
 * @Version: 1.0
 */
public class LeaderListener implements ExecutionListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(LeaderListener.class);

    @Override
    public void notify(DelegateExecution execution) {
        String executionId = execution.getId();
        String processId = execution.getProcessInstanceId();
        String definitionId = execution.getProcessDefinitionId();
        String currentActivityId = execution.getCurrentActivityId();
        String assignee = null;
        TaskEntity task = FlowService.taskService().getTaskByExecutionId(executionId);
        if (task != null) {
            assignee = task.getAssignee();
        }
        if (assignee == null) {
            //获取上一个节点的办理用户ID
            List<HistoricTaskInstance> historicTaskInstances = FlowService.taskService().getHistoricTaskInstanceByProcessId(processId);
            if (historicTaskInstances.size() > 0) {
                HistoricTaskInstance historicTaskInstance = historicTaskInstances.get(historicTaskInstances.size() - 1);
                assignee = historicTaskInstance.getAssignee();
            }
        }
        if (StringUtils.isEmpty(assignee)) {
            assignee = SecurityUtils.getCurrentUserId();
        }

        // 获取领导用户
        FlowUser leader = FlowService.identityService().getUserByUserId("yang");
        checkState(leader != null, "无法获取用户 {} 的领导用户", assignee);
        execution.setVariable(FlowConstants.Assignee.SINGLEUSER.getAssignee(), leader.getUser().getId());

    }
}
